<template>
    <div>
        <el-dialog :title="title" v-model="show" width="600px" append-to-body draggable :close-on-click-modal="false"
            align-center>
            <el-form ref="deptRef" :model="orgForm" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="24" v-if="orgForm.parentId != 0">
                        <el-form-item label="上级组织" prop="parentId">
                            <el-tree-select v-model="orgForm.parentId" :data="orgOptions" disabled
                                :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id"
                                placeholder="选择上级组织" check-strictly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="组织机构" prop="name">
                            <el-input v-model="orgForm.name" placeholder="请输入组织机构" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="组织编码" prop="code">
                            <el-input v-model="orgForm.code" placeholder="请输入编码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="组织类型" prop="type">
                            <el-tag type="primary" effect="dark">
                                <IconPlus v-if="orgType.icon" :name="orgType.icon" />
                                {{ orgType.label }}
                            </el-tag>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="负责人" prop="managerId">
                            <el-input :value="orgForm.manager?.nickName" readonly placeholder="请选择负责人" maxlength="20"
                                clearable suffix-icon="Search" @click="handleUserSelect" />
                            <el-input v-show="false" v-model="orgForm.managerId" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" prop="mobile">
                            <el-input v-model="orgForm.mobile" placeholder="请输入联系电话" maxlength="11" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="orgForm.email" placeholder="请输入邮箱" maxlength="50" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="部门状态">
                            <el-radio-group v-model="orgForm.isActive">
                                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">
                                    {{ dict.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="显示排序" prop="order">
                            <el-input-number v-model="orgForm.order" controls-position="right" :min="0" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-show="operation == 2">
                    <el-divider content-position="left">审计信息</el-divider>
                    <el-col :span="12">
                        <el-form-item label="创建于" prop="updateTime">
                            <el-date-picker v-model="orgForm.createdAt" type="datetime" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="创建人" prop="updateTime">
                            <el-input v-model="orgForm.creator" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="更新于" prop="updateTime">
                            <el-date-picker v-model="orgForm.updatedAt" type="datetime" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="修改人" prop="updateBy">
                            <el-input v-model="orgForm.updater" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm" v-show="operation == 1 || operation == 0">确
                        定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <UserSelect ref="userSelectRef" @select="onSelected" :data="[orgForm.manager]" />
    </div>
</template>

<script setup>
import { org_type } from "./dict"
import { deepClone } from "@/utils"
import { addDept, updateDept } from "@/api/system/dept";
import UserSelect from "@/components/UserSelect";
const { proxy } = getCurrentInstance()
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const emits = defineEmits(["onSuccess", "onCancel"])

const userSelectRef = ref();
const orgForm = ref({});
const operation = ref();  // 操作类型：add 0、edit 1、view 2
const show = ref(false);
const rules = {
    // parentId: [{ required: true, message: "上级组织不能为空", trigger: "blur" }],
    name: [{ required: true, message: "组织机构不能为空", trigger: "blur" }],
    code: [
        { required: true, message: "编码不能为空", trigger: "blur" },
        { pattern: /^[A-Z0-9-]+$/, message: "编码只能包含大写字母、数字和短横线", trigger: "blur" },
        { min: 3, max: 20, message: "编码长度必须在 3 到 20 个字符之间", trigger: "blur" },
    ],
    order: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
    email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
    mobile: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
}

const { loading, orgOptions } = defineProps({
    loading: { type: Boolean, default: true },
    orgOptions: { type: Array, default: [] }
})

const orgType = computed(() => {
    return org_type.find(item => item.value == orgForm.value.type) || {};
})

const title = computed(() => {
    switch (operation.value) {
        case 0: return "新增组织";
        case 1: return "编辑组织";
        case 2: return "查看组织";
    }
});


/** 提交按钮 */
function submitForm() {
    proxy.$refs["deptRef"].validate().then(res => {
        // 定义处理操作成功后的通用逻辑函数
        const handleSuccess = () => {
            proxy.$modal.msgSuccess(orgForm.value.id !== undefined ? "修改成功" : "新增成功");
            open.value = false;
            emits("onSuccess", orgForm.value)
            cancel();
        };
        const operationPromise = orgForm.value.id !== undefined ? updateDept(orgForm.value) : addDept(orgForm.value);
        operationPromise.then(handleSuccess);
    })
}


/** 取消按钮 */
function cancel() {
    show.value = false;
    reset();
}

/** 表单重置 */
function reset() {
    orgForm.value = {
        id: undefined,
        parentId: undefined,
        name: undefined,
        order: 0,
        managerId: undefined,
        mobile: undefined,
        email: undefined,
        type: undefined,
        isActive: true,
        manager: {}
    };
    proxy.resetForm("deptRef");
}

/**设置组织机构数据 */
const setOrg = (org) => {
    orgForm.value = deepClone(org)
}

/**开始编辑组织机构 */
const editOrg = () => {
    show.value = true;
    operation.value = 1;
}

/**添加组织机构 */
const addOrg = () => {
    show.value = true;
    operation.value = 0;
}

/** 查看组织机构 */
const viewOrg = () => {
    show.value = true;
    operation.value = 2;
}

defineExpose({ setOrg, editOrg, addOrg, viewOrg })

const handleUserSelect = ($event) => {
    // 打开用户选择弹窗
    userSelectRef.value.open()
}

/** 用户选择回调 */
const onSelected = (user) => {
    if (user) {
        orgForm.value.managerId = user.id;
        orgForm.value.manager = user;
    }
}

</script>

<style lang="scss" scoped>
.org-type {
    display: flex;
    gap: 6px;
    align-items: center;
}
</style>
